/*
 * Copyright 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
 */
package src.com.bjsxt.height.design015_test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Description:
 *
 * @author wzz
 * @since: 1.0
 * Create Date Time: 2018/10/31 10:43
 * Update Date Time:
 */
public class Master {

    //1.有一个放任务的容器(放任务)
    private ConcurrentLinkedQueue<Task> workQueue = new ConcurrentLinkedQueue<>();
    //2.需要一个盛放work的集合(放work)
    private Map<String,Thread> works = new HashMap<>();
    //3.需要一个盛放每个work处理完结果的集合(放结果)
    private ConcurrentHashMap<String,Object> resulMap = new ConcurrentHashMap();
    //4.构造方法
    public Master(Work work,int count){
        work.setWorkQueue(this.workQueue);
        work.setResultMap(this.resulMap);

        for(int i=0;i<count;i++){
            works.put(Integer.toString(i),new Thread(work));
        }
    }
    //5.需要一个提交方法
    public void submit(Task task){
        workQueue.add(task);
    }
    //6.需要一个执行方法,去启动所有的work
    public void excute(){
        for(Map.Entry<String,Thread> me:works.entrySet()){
            me.getValue().start();
        }
    }
    //7.判断是否运行结束的方法
    public boolean isComplete(){
        for(Map.Entry<String,Thread> me :works.entrySet()){
            if(me.getValue().getState() != Thread.State.TERMINATED){
                return false;
            }
        }
        return true;
    }
    //8.计算结果方法
    public int getResult() {
        int priceResult = 0;
        for(Map.Entry<String, Object> me : resulMap.entrySet()){
            priceResult += (Integer)me.getValue();
        }
        return priceResult;
    }
}
